/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package catalog;

import java.io.IOException;
import java.util.HashSet;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.util.HashSet;
/**
 *
 * @author smoniz
 * I used http://www.java-samples.com/showtutorial.php?tutorialid=152 heavily in building my XML parser
 */
public class XMLParser {
//
    //Reference

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Document xml = parseXmlFile("./dat/cd.xml"); //path of the xml file
        Catalog cat = parseDoc(xml);
        cat.printCDs();

        System.out.println(cat.getGenres());

        HashSet<String> hs = new HashSet<String>();
        hs.add("Rap");
        hs.add("Jazz");
        System.out.println(cat.getArtists(hs.toArray()));
        
    }

    public static Catalog getCatalog() {
        Document xml = parseXmlFile("./dat/cd.xml"); //path of the xml file
        Catalog cat = parseDoc(xml);
        return cat;

    }

    public static Catalog getCatalog(String path) {
        Document xml = parseXmlFile(path); //path of the xml file
        Catalog cat = parseDoc(xml);
        return cat;
    }

    /**
     * Paarses a document object into a catalog of CDs
     * @param doc
     * @return
     */
    private static Catalog parseDoc(Document doc) {
        Element docElement = doc.getDocumentElement();
        Catalog cat = new Catalog();
        NodeList nl = docElement.getElementsByTagName("cd");
        if (nl != null && nl.getLength() > 0) {
            for (int i = 0; i < nl.getLength(); i++) {
                CD cd = CD.fromXMLElement((Element) nl.item(i));
                cat.addCD(cd);


            }



        }
        return cat;

    }

    /**
     * Parses an XML file into a document object
     * @param path
     * @return
     */
    public static Document parseXmlFile(String path) {
        //get the factory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {

            //Using factory get an instance of document builder
            DocumentBuilder db = dbf.newDocumentBuilder();
            //          File file = new File()
            //parse using builder to get DOM representation of the XML file
            Document dom = db.parse(path);
            return dom;

        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (SAXException se) {
            se.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return null;
    }
}
